package com.kaviddiss.bootquartz.thread;

import com.kaviddiss.bootquartz.job.SampleJob;
import com.kaviddiss.bootquartz.service.SampleService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by Studio on 2017/5/18.
 * 经历了萌豆 优酱 黄大蒜等一众洗礼后
 *
 */
@Component
public class TestThread extends Thread{

    @Autowired
    private Scheduler scheduler;

    private static final Logger LOG = LoggerFactory.getLogger(SampleService.class);

    private static TestThread testThread;

    public TestThread() {
    }

    @PostConstruct     //关键二   通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
    public void init() {
        testThread = this;
        testThread.scheduler = this.scheduler;
    }

    @Override
    public void run ()  {
        Class sampleJob = null;
        try {
            sampleJob = Class.forName("com.kaviddiss.bootquartz.job.SampleJob");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        JobDetail jobDetail = JobBuilder.newJob(sampleJob)
//        JobDetail jobDetail = JobBuilder.newJob(SampleJob.class)
                .storeDurably(true)
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .startNow()
                .build();

        LOG.info("Scheduler");
        try {
            testThread.scheduler.scheduleJob(jobDetail, trigger);
            testThread.scheduler.start();
            Thread.sleep(10000);
        } catch (SchedulerException | InterruptedException e) {
            e.printStackTrace();
        }

    }

}
